package com.adam.springsecurity;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.file.AccessDeniedException;

@Controller
@RequestMapping("/error")
@Slf4j
public class ErrorController {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;

    @RequestMapping("/403")
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public ModelAndView error403() {
        log.info("custom 403");
        ModelAndView modelAndView = new ModelAndView("error403");
        Object exceptionObject = request.getAttribute(WebAttributes.ACCESS_DENIED_403);
        if(exceptionObject instanceof AccessDeniedException) {
            AccessDeniedException exception = (AccessDeniedException) exceptionObject;
            modelAndView.addObject("err", exception.getClass().getName() + ":" + exception.getMessage());
        }
        return modelAndView;
    }

}
